package com.lhl.api.advice;


import cn.hutool.json.JSONUtil;
import com.lhl.api.annotation.IgnorReponseAdvice;
import com.lhl.api.config.ApiFilterConfig;
import com.lhl.fw.core.base.PageDTO;
import com.lhl.fw.core.base.ResultDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * @className: ApiResponseDataAdvice
 * @description: TODO 类描述
 * @author: king
 * @date: 2020-09-09 11:01
 **/
@RestControllerAdvice
@Slf4j
public class ApiResponseDataAdvice implements ResponseBodyAdvice<Object> {
    private ApiFilterConfig apiFilterConfig;

    public ApiResponseDataAdvice(ApiFilterConfig apiFilterConfig) {
        this.apiFilterConfig = apiFilterConfig;
    }

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = Objects.requireNonNull(attributes).getRequest();
        String uri = request.getRequestURI();
        log.debug("uri=={}",uri);
        if(uri.startsWith("/swagger-resources")
                || uri.startsWith("/v3/api-docs")
                || uri.startsWith("/wx/cp/portal")){
            return false;
        }
        return filter(returnType);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body== null) {
//            return new ResultDTO().ofSuccess();
            return ResultDTO.builder().succ(true).ts(System.currentTimeMillis()).build();
        }
        // o is instanceof ConmmonResponse -> return o
        if (body instanceof ResultDTO) {
            return (ResultDTO<Object>) body;
        }
        // string 特殊处理
        if (body instanceof String) {
            return JSONUtil.toJsonStr(ResultDTO.builder().succ(true).ts(System.currentTimeMillis()).data(body).build());
        }
        //自定义分页处理
        if (body instanceof PageDTO) {
            return ResultDTO.builder().succ(true).ts(System.currentTimeMillis())
                    .total(((PageDTO) body).getTotal())
                    .data(((PageDTO) body).getContent()).build();
        }
        /*//springdata分页处理
        if (body instanceof Page) {
            return ResultDTO.ofSuccess(((Page) body).getContent(),((Page) body).getTotalElements());
        }
        //mybatis分页处理
        if (body instanceof PageInfo) {
            return ResultDTO.ofSuccess(((PageInfo) body).getList(),((PageInfo) body).getTotal());
        }*/
        return ResultDTO.builder().succ(true).ts(System.currentTimeMillis()).data(body).build();
    }

    private Boolean filter(MethodParameter methodParameter) {
        //返回值类型是ResultDTO,则不必加工
        if(methodParameter.getMethod().getReturnType().getName().equals(ResultDTO.class.getName())){
            return false;
        }
        Class<?> declaringClass = methodParameter.getDeclaringClass();

        // 检查过滤包路径
        long count = apiFilterConfig.getAdviceFilterPackage().stream()
                .filter(l -> declaringClass.getName().contains(l)).count();
        if (count > 0) {
            return false;
        }
        // 检查<类>过滤列表
        if (apiFilterConfig.getAdviceFilterClass().contains(declaringClass.getName())) {
            return false;
        }
        // 检查注解是否存在
        if (methodParameter.getDeclaringClass().isAnnotationPresent(IgnorReponseAdvice.class)) {
            return false;
        }
        if (methodParameter.getMethod().isAnnotationPresent(IgnorReponseAdvice.class)) {
            return false;
        }
        return true;
    }
}